package com.fansl.allround.message.server;

import com.alibaba.fastjson.JSONObject;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOServer;
import com.fansl.allround.message.api.constant.SocketConstant;
import com.fansl.allround.message.api.message.ChatMessage;
import com.fansl.allround.message.listenner.ChatEventListener;
import com.fansl.allround.message.listenner.EventListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author fansl
 * @Description: TODO
 * @date 2019/9/4 17:03
 */
@Slf4j
@Component
public class PushServer implements InitializingBean {
    @Resource
    private ChatEventListener chatEventListener;
    @Resource
    private EventListener eventListener;

    @Value("${push.server.port}")
    private int serverPort;
    @Value("${push.server.host}")
    private String serverHost;
    @Override
    public void afterPropertiesSet() throws Exception {
        Configuration cfg = new Configuration();
        cfg.setPort(serverPort);
        cfg.setAuthorizationListener(handshakeData -> {
            log.info("handshakeData:{}",JSONObject.toJSONString(handshakeData));
            return true;
        });

        SocketConfig socketConfig = new SocketConfig();
        socketConfig.setReuseAddress(true);
        socketConfig.setTcpNoDelay(true);
        socketConfig.setSoLinger(0);

        cfg.setSocketConfig(socketConfig);
        cfg.setHostname(serverHost);

        SocketIOServer socketIOServer = new SocketIOServer(cfg);
        socketIOServer.addListeners(eventListener);
        socketIOServer.addEventListener(SocketConstant.SocketEvent.ChatEvent,ChatMessage.class,chatEventListener);
        socketIOServer.start();
        log.info("推送消息服务启动");
    }
}
